import router from './router'

// 全局变量
const tabList = [];
const currentTab =  '';
 // tab页的集合 {name, path} 存的路由的名称和路径
const routerList = []; // 路由集合用来生成菜单
// 将路径拼接成字符串
function getViews(component) {
    return (resolve) => {
        require.ensure([], (require) => {
            resolve(require('@/views/' + component + '.vue'))
        })
    }
}
// 根据后台的数据生成符合标准的router格式
function generateRouterDate(oridata) {
    for (let i=0; i<oridata.length;i++){
        for (let i=0; i<oridata.length;i++){
            oridata[i]['path'] = oridata[i]['funPath'];
            oridata[i]['name'] = oridata[i]['funName'];
            oridata[i]['icon'] = oridata[i]['funIcon'];
            oridata[i]['absPath'] = oridata[i]['funAbsPath'];
            oridata[i]['component'] = getViews(oridata[i].funContent);
            if(null!= oridata[i]['children'] && oridata[i]['children'].length>0){
                this.generateRouterDate(oridata[i]['children']);
            }
        }
    }
}
function addTab({name,absPath,funIcon}) {
    for(let tab of this.tabList) {
        if(tab.name == absPath) {
            this.currentTab = absPath;
            return;
        }
    }
    this.tabList.push({
        title: name,
        name: absPath,
        icon: funIcon,
        content: ''
    });
    this.currentTab = absPath;
}
function removeTab(targetName) {
    let tabs = this.tabList;
    let activeName = this.currentTab;
    if (activeName === targetName) {
        tabs.forEach((tab, index) => {
            if (tab.name === targetName) {
                let nextTab = tabs[index + 1] || tabs[index - 1];
                if (nextTab) {
                    activeName = nextTab.name;
                }
            }
        });
    }
    this.currentTab = activeName;
    this.tabList = tabs.filter(tab => tab.name !== targetName);
    // 跳转到当前选中界面
    router.push(activeName)
}

function selectTab(tab) {
    if(tab.name == router.path) {
        return;
    }
    router.push(tab.name)
}

tabList.push({
    title: '首页',
    name: '/main/dashboard',
    content: '',
    icon: 'el-icon-s-home',
    closable: true
});
export default {
    tabList,
    currentTab,
    routerList,
    addTab,
    removeTab,
    generateRouterDate,
    selectTab,
}